using System;
using Framework.FSMLite;
using Framework.Timer;
using Framework.UI;
using StateSystem.Loader;
using UnityEngine;
using View;

namespace StateSystem.State
{
    public class StateLoading : StateMachine<StateSystem.GameState>
    {

        private GameState _targetState;
        private ILoader   _loader;

        protected override void OnEnter(params object[] args)
        {
            UIManager.Instance.OpenView(UIPanel.LoadingPanel);
            if (args[0] is GameState)
            {
                this._targetState = (GameState) args[0];
                GameUpdateMgr.Instance.CreateTimer((float) args[1], () => { this.stateMachineRunner.OpenState(this._targetState); });
            }
            else
            {
                this._loader = (ILoader) args[0];
                this._targetState = (GameState) args[1];
                this._loader.BeginLoad(this.OnLoading, this.OnLoadComplete);
            }
        }

        private void OnLoading(float progress)
        {
            if (progress == 0.9f)
            {
                GameUpdateMgr.Instance.CreateTimer(1 , ()=>{
                    UIManager.Instance.GetViewModule<LoadingPanel>(UIPanel.LoadingPanel).CloseBG();
                });
                GameUpdateMgr.Instance.CreateTimer(2.5f,
                                                    () =>
                                                    {
                                                        this._loader.Active();
                                                    });
            }
        }

        private void OnLoadComplete()
        {
            this.stateMachineRunner.OpenState(this._targetState);
        }

        protected override void OnExit() { UIManager.Instance.CloseView(UIPanel.LoadingPanel); }

    }
}